﻿using System;
using System.Collections.Generic;
using System.Linq;
using Dolany.UtilityTool;
using Missbot.Core.Cache;
using Missbot.Core.Common;
using Missbot.Core.Scheduler;
using Missbot.Model.MsgCmds.Notes;
using Missbot.Model.MsgInfos;
using Missbot.Service.Dingtalk;
using Missbot.WeiboBot;

namespace Missbot.AIModule.Schedulers.WeiboBot
{
    /// <summary>
    /// 微博机器人定时器基类
    /// </summary>
    public abstract class IWeiboBotScheduler : IScheduler
    {
        protected sealed override List<ScheduleMeta> ModelList { get; set; }

        protected sealed override void ScheduleDo(SchedulerTimer timer)
        {
        }

        /// <summary>
        /// 拉取微博时间间隔
        /// </summary>
        protected virtual TimeSpan FetchSpan { get; } = TimeSpan.FromHours(1);

        /// <summary>
        /// 发送嘟文时间间隔
        /// </summary>
        protected virtual TimeSpan TootSpan { get; } = TimeSpan.FromMinutes(10);

        /// <summary>
        /// 微博原博用户ID
        /// </summary>
        protected abstract long UID { get; }

        private WeiboRequestor Requestor;

        public override void Work()
        {
            Requestor = new WeiboRequestor(UID);

            SchedulerSvc.Add(new IntervalSpan { Interval = FetchSpan }, Fetch, IsImmdiately: true);
            SchedulerSvc.Add(new IntervalSpan { Interval = TootSpan }, Toot, IsImmdiately: true);
        }

        /// <summary>
        /// 拉取微博信息列表
        /// </summary>
        /// <param name="timer"></param>
        private void Fetch(SchedulerTimer timer)
        {
            var resp = Requestor.GetList();
            var key = $"Weibo_{Owner}:IsAlerting";
            var isAlerting = RapidCacher.GetBool(key);
            if (resp == null)
            {
                // 不重复警告
                if (isAlerting)
                {
                    return;
                }

                DingtalkSvc.Send($"Weibo_{Owner}: Response Error!");
                RapidCacher.SetBool(key, true, DateTime.Now.AddDays(1));
                return;
            }

            // 刷新警告信息
            RapidCacher.SetBool(key, false, DateTime.Now.AddDays(1));

            var parser = new WeiboParser(Owner, UID);
            var list = parser.Parse(resp);
            if (list.IsNullOrEmpty())
            {
                return;
            }

            StatusEnqueue(list);
        }

        /// <summary>
        /// 微博消息入队
        /// </summary>
        /// <param name="list"></param>
        private void StatusEnqueue(IEnumerable<WeiboStatusRec> list)
        {
            foreach (var rec in list)
            {
                if (WeiboStatusRecDA.IsExist(rec.StatusID))
                {
                    continue;
                }

                rec.Insert();
            }
        }

        /// <summary>
        /// 从队列中获取微博消息并发送
        /// </summary>
        /// <param name="timer"></param>
        private void Toot(SchedulerTimer timer)
        {
            var rec = WeiboStatusRecDA.GetStatus(Owner);
            if (rec == null)
            {
                return;
            }

            if (rec.Files.IsNullOrEmpty())
            {
                if (!string.IsNullOrEmpty(rec.Text))
                {
                    MsgSender.PushMsg(new CreateNoteCmd { Text = rec.Text });
                }
            }
            else
            {
                var fileIDs = UploadFiles(rec).Select(p => p.ID).ToArray();
                if (!fileIDs.IsNullOrEmpty())
                {
                    MsgSender.PushMsg(new CreateNoteWithFileCmd { Text = rec.Text, FileIDs = fileIDs });
                }
            }

            rec.IsTooted = true;
            rec.Update();
        }

        private IEnumerable<InstanceFile> UploadFiles(WeiboStatusRec rec)
        {
            return rec.Files.IsNullOrEmpty() ? null : rec.Files.Select(url => FileUploader.PicUpload(null, url)).Where(f => f != null).ToArray();
        }
    }
}